﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DDS.IoT.Com;

namespace MyWebCom
{
    public class MyTestCom : ComBase
    {
        public override string Type => "myTestCom";

        public override string Name => "我的测试串口";

        public override event PushData OnPushData;
        private string _extendData = null;

        public override bool Close()
        {
            Console.WriteLine("关闭成功");
            IsOpen = false;
            OnPushData = null;// 注意一定要设置为null
            return true;
        }

        public override bool Init(int port, int baudRate = 9600, string extendData = null)
        {
            this.Port = port;
            //真实场景中，应该实现串口实例化操作
            //base.SP = new System.IO.Ports.SerialPort();
            Console.WriteLine("初始化成功：" + extendData);
            _extendData = extendData;
            return true;
        }

        public override bool Open()
        {
            if (!IsOpen)
            {
                Console.WriteLine("打开成功");
                IsOpen = true;
                Task.Run(() => {
                    while (this.IsOpen)
                    {
                        var val = "来自MyTestCom " + (new Random().NextDouble() * 100).ToString("N1");
                        SendData(val);

                        Thread.Sleep(300);
                    }
                });
            }
            else
            {
                Console.WriteLine("已打开");
            }
            return true;
        }
        /// <summary>
        /// 往客户端界面推送数据
        /// </summary>
        /// <param name="data"></param>
        private void SendData(dynamic data)
        {

            if (OnPushData != null)
            {
                Data = data;
                // 调用代理事件
                OnPushData(this.Id, Data);
            }
        }
        /// <summary>
        /// 发送数据接口
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public override string Send(string data)
        {
            Console.WriteLine("接收到数据：" + data);
            SendData("来自MyTestCom接收到数据：" + data);
            return base.Send(data);
        }
    }
}
